/*
 * Implementation of Thesaurus class.
 */

#include <QtGui>

#include "includes/thesaurus.h"
#include "includes/phrase.h"
#include "includes/phrasecollection.h"

#include <QtDebug>

Thesaurus::Thesaurus() {
	// init
}

// populate thesaurus from phrase collection.
// use hash table instead of nested sequential search
Thesaurus::Thesaurus(PhraseCollection& phrases) {
	populate(phrases);
}

// populate the thesaurus from given PhraseCollection.
// synonyms are added to the thesaurus
void Thesaurus::populate(PhraseCollection& phrases) {
	// iterate through phrases
        for (PhraseCollection::iterator it = phrases.begin(); it != phrases.end(); ++it) {
		// pull out next phrase
                Phrase *phrase = &(*it);

		// add the phrase itself
                //stringToPhrasesMap.insert(phrase->getName().toLower(), phrase);
                addWithSubstrings(phrase->getName(), phrase);

		// iterator through each phrases' synonyms
                QStringList synonyms = phrase->getSynonyms();
		QListIterator<QString> synonymIt(synonyms);
		while (synonymIt.hasNext()) {
			// pull value out of interator and increment
			QString synonym = synonymIt.next();
			// add synonym; map to phrase.
			// will be added to multi entry if already exists.
			// note: lowercase
                        //stringToPhrasesMap.insert(synonym.toLower(), phrase);
                       // qDebug() << "Adding synonym:" << synonym << endl;
                        addWithSubstrings(synonym, phrase);
		}
	} 
}

// add a word and all its substrings
void Thesaurus::addWithSubstrings(const QString& word, Phrase* phrase) {
    // recursive
    if (word.length() > 0) {
        stringToPhrasesMap.insert(word.toLower(), phrase);
        addWithSubstrings(word.left(word.length()-1), phrase);
    }
}


// lookup word. return NULL by default.
QList<Phrase*> Thesaurus::lookup(const QString& word) {
	// values() for multi hash table
	// (use value() so we don't accidentally insert the word we're looking for) ?
	return stringToPhrasesMap.values(word.toLower());
}
